package com.ruoyi.utils;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Page 构建工具
 *
 * @author liuliya
 */
public class PageUtil {

    public static final long pageNo = 1;
    public static final long pageSize = 20;

    /**
     * 构建分页条件
     * @param query
     * @param <T>
     * @return
     */
    public static <T> Page<T> buildPage(PageQuery query) {
        return buildPage(query, false);
    }

    /**
     * 构建分页条件
     * @param query
     * @param isSort 是否排序
     * @param <T>
     * @return
     */
    public static <T> Page<T> buildPage(PageQuery query, boolean isSort) {
        Page<T> page = new Page<>(ObjectUtils.isEmpty(query.getPageNo()) ? pageNo : query.getPageNo(),
                ObjectUtils.isEmpty(query.getPageSize()) ? pageSize : query.getPageSize());
        if (isSort) {
            if (StringUtils.isNotBlank(query.getAscs())) {
                List<OrderItem> ascs = Arrays.stream(query.getAscs().split(StringPool.COMMA))
                        .map(asc -> OrderItem.asc(asc.trim())).collect(Collectors.toList());
                page.addOrder(ascs);
            }
            if (StringUtils.isNotBlank(query.getDescs())) {
                List<OrderItem> descs = Arrays.stream(query.getDescs().split(StringPool.COMMA))
                        .map(desc -> OrderItem.desc(desc.trim())).collect(Collectors.toList());
                page.addOrder(descs);
            }
        }
        return page;
    }

}
